<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\kuaishou;

use app\enum\KsCodeEnum;
use app\enum\KuaiShouEnum;
use app\enum\KuaiShouUrlEnum;
use app\model\ClientAccountModel;
use app\model\MediaAccountModel;
use app\model\MediaTokenModel;
use app\service\BaseService;
use app\service\client\AccountService;
use app\service\MediaTokenInterface;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Model;

class TokenService extends BaseService implements MediaTokenInterface
{
    /**
     * 刷新快手系广告账户拉取权限.
     * @param Model $obj MediaTokenModel模型
     * @param ClientAccountModel $account 账户模型
     */
    public static function refreshAdv(Model $obj, ClientAccountModel $account): bool
    {
        if (! $obj instanceof MediaTokenModel || ! $obj->getKey()) {
            return self::setError('Token信息不存在');
        }
        if (! $account instanceof ClientAccountModel || ! $account->getKey()) {
            return self::setError('账户信息不存在');
        }
//        $mediaModel = (new MediaAppModel())->where('id', '=', $obj->media_app_id)->find();
//        if (! $mediaModel instanceof MediaAppModel || ! $mediaModel->getKey()) {
//            return self::setError('APP信息不存在');
//        }
        try {
            $redis = Cache::store('redis')->handler();
            $token = $redis->get($obj->getAttr('redis_key'));
            $param = [
                'advertiser_id' => $account->getAttr('advertiser_id'),
            ];
            $serviceName = KuaiShouUrlEnum::getServiceName('advertiser');
            $serviceUrl = KuaiShouUrlEnum::getServiceUrl('token', 'advertiser_info');
            $serviceMethod = 'getJson';
            $serviceHeader = [
                'Access-Token' => $token,
                'Content-Type' => 'application/json',
            ];
            $res = self::send($serviceName, $serviceUrl, $param, $serviceMethod, $serviceHeader);
            if ($res['code'] != KuaiShouEnum::RESPONSE_SUCCESS_CODE) {
                return self::setError('刷新[' . $obj->id . ']账户失败:' . $res['code'] . '-' . $res['message']);
            }
            // 拉取成功
            $model = new MediaAccountModel();
            $model->media_token_id = $obj->getKey();
            $model->account_id = $account->getKey();
            $model->advertiser_id = $account->advertiser_id;
            if ($model->save()) {
                return true;
            }
            return self::setError('新增[' . $account->advertiser_id . ']token失败');
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 根据refresh_token刷新token.
     * @param string $appId app_id
     * @param string $appSecret secret
     * @param string $refreshToken refreshToken
     * @return bool|mixed
     */
    public static function refreshToken(string $appId = '', string $appSecret = '', string $refreshToken = '')
    {
        $param = [
            'app_id' => $appId,
            'secret' => $appSecret,
            'refresh_token' => $refreshToken,
        ];
        $serviceName = KuaiShouUrlEnum::getServiceName('advertiser');
        $serviceUrl = KuaiShouUrlEnum::getServiceUrl('advertiser', 'refresh_token');
        $serviceMethod = 'postJson';
        $serviceHeader = ['Content-Type' => 'application/json'];
        $res = self::send($serviceName, $serviceUrl, $param, $serviceMethod, $serviceHeader);
        if ($res['code'] != KsCodeEnum::SUCCESS) {
            return self::setError($res['message']);
        }
        return $res;
    }

    /**
     * 获取接口账户信息.
     * @param int $accountId 账户id
     * @param string $token token值
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAccountInfo(int $accountId = 0, string $token = ''): bool
    {
        // 获取账户信息
        $account = AccountService::getAccountModel($accountId);
        if (! $account instanceof ClientAccountModel && ! $account->getKey()) {
            return self::setError('账户信息不存在');
        }
        $header = [
            'Content-Type' => 'application/json',
            'Access-Token' => $token,
        ];
        $params = ['advertiser_id' => $account->getAttr('advertiser_id')];
        $res = AdvertiserService::getAccountInfo($header, $params);
        if ($res['code'] == KsCodeEnum::SUCCESS) {
            return true;
        }
        return false;
    }
}
